'use strict'

define([ 'jquery', 'bootstrap', 'select2', 'bodyform', 'shiftform', 'validate',
    'validate.en'], function($) {
  return {
    init : function() {
      this.initPage();
      this.initSelect2();
      this.scoreSelect2();
      this.initChoice(); 
      this.initShowDetail();
      this.submitTab();
      this.submitScore();
    },
    
    initPage : function() {
      $(".autosize-textarea").autosize();
    },
    
    initSelect2: function() {
      var that = this;
      var data = that._generateSelectData();
      $('select.select2').select2({
        theme : "classic",
        placeholder : $(this).data("placeholder"),
        minimumResultsForSearch : -1,
        allowClear : true,
      }).on('change', function() {
        if(this.value) {
          var select2Data = that._calculateSelect2(data, $(this).find(":selected").data("name"))
          var name = $(this).attr('name');
          $(this).parent().next().find("input[name='choose']").val(this.value);
          $('input[name="'+ name + 'Title"]').select2({
            placeholder : $(this).data("placeholder"),
            minimumResultsForSearch : -1,
            allowClear : true,
            data: function() { return {results: select2Data}; }
          }).on('change', function(){
            if(this.value == 'other') {
              $(this).after('<input type="text" name="'+name+'Other" class="form-control" style="margin-top: 10px;" placeholder="other title" />');
              $('textarea[name="'+ name + 'Comment"]').val('');
            } else {
              $('textarea[name="'+ name + 'Comment"]').val(that._generateTextarea(this.value));
            }
          });
          $('input[name="'+ name + 'Title"]').select2('val', '').removeClass("hide");
        } else {
          $('textarea[name="'+ name + 'Comment"]').val('');
          $('textarea[name="'+ name + 'Other"]').remove();
          $('input[name="'+ name + 'Title"]').select2('val', '').addClass("hide");
        }
      });
      
    },
    
    scoreSelect2: function() {
      if(!$("select[name='score']").val()) {
         $(".visibility").css("visibility", "hidden")
       } else {
         $(".visibility").css("visibility", "visible")
       }
   
      $("select[name='score']").on("change", function() {
        if($("select[name='score']").val()) {
          $(".visibility").css("visibility", "visible")
        } else {
          $(".visibility").css("visibility", "hidden")
        }
      })
      
    },
    
    _generateSelectData : function() {
      var data = {};
      $(".messages").find("div.com").each(function(){
        var key = $(this).data("com");
        var values = [];
        $(this).find("div.anchor").each(function(){
          var anchorJson = {};
          $(this).find("input").each(function() {
            anchorJson[$(this).attr("name")] = $(this).val();
          })
          values.push(anchorJson);
        })
        data[key] = values;
      })
      return data;
    },
    
    _calculateSelect2(data, key) {
      var arrays = data[key];
      var result = [];
      for(var item in arrays) {
        var value = {};
        value['id']=arrays[item].name;
        value['text']=arrays[item].name;
        result.push(value)
      }
      result.push({'id': 'other', 'text': 'other'})
      return result;
    },
    
    _generateTextarea(value) {
      var $parent = $('input[value="'+value+'"]').parent();
      var score = $parent.find("input[name='score']").val().toLowerCase();
      var text = $parent.find("input[name='"+score+"Desc']").val();
      console.log(text);
      return text;
    },
    
    initChoice: function() {
      $(document).on("click", ".recommendation input[type='checkbox']", function() {
        if(!$(this).prop("checked")) {
        	$(this).parents("tr").find("input[type='checkbox']").prop("disabled", false)
        } else {
          $(this).parents("tr").find("input[type='checkbox']").prop("disabled", true)
          $(this).prop("disabled", false)
        }
      })
    },
    
    initShowDetail: function() {
      $(document).on('click', '.anchor-link', function(e) {
        var currentIndex = $(e.currentTarget).data("option");
        $(".scoring-details").eq(currentIndex).show().siblings().hide();
      })
      
      $(document).on('click', '.close-details', function(e) {
        $(".scoring-details").hide();
      })
    },
    
    submitTab: function() {
      var that = this;
      
      var temp = false;
      $('.competency-item').change(function() {
    	  temp = true;
      })
      
      $(document).on("click", ".submit-tab a", function(e){
        var $form = $('form[data-validate="true"]')
        var url = $(this).data("href");
        if(temp) {
        	$form.unbind("click");
            $form.bodyform({
              showModal: false,
              beforeSubmit : function(el) {
                $form.trigger("validate.ajax.submit");
                var result = $.bt_validate.result[$.bt_validate.form_id];
                if(!result) {
                  return result;
                }
                return that.validateForm();
              },
              success: function() {
                window.location.href = url;
              }
            })
            $form.find("button[type='submit']").click();
        } else {
        	window.location.href = url;
        }
        
      })
    },
    
    submitScore: function() {
      var that = this;
      var $form = $('form[data-validate="true"]')
      $form.bt_validate()  //bind validate
      $form.bodyform({
        beforeSubmit : function(el) {
          $form.trigger("validate.ajax.submit");
          var result = $.bt_validate.result[$.bt_validate.form_id];
          if(!result) {
            return result;
          }
          return that.validateForm();
        }
      })
    },
    
    validateForm: function() {
      
      var strongLength = $("input[name='strong']:checked").length;
      if(strongLength  == 0) {
        $('p.strong-weak').show_tooltip($('p.strong-weak').text(),'remove', '#F2DEDE', '#EBCCD1', '#B94A48');
        return false;
      }
      
      var weakLength = $("input[name='weak']:checked").length;
      if(weakLength  == 0) {
        $('p.strong-weak').show_tooltip($('p.strong-weak').text(), 'remove', '#F2DEDE', '#EBCCD1', '#B94A48');
        return false;
      }
      
      return true;
      
    }
    
  }
})
